package com.xln.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xln.interceptor.AdminTokenInterceptor;
import com.xln.pojo.Admin;
import com.xln.pojo.Article;
import com.xln.service.ArticleService;
import com.xln.service.CategoryService;
import com.xln.util.ResEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class ArticleContoller {

    @Resource
    private ArticleService articleService;

    @Resource
    private CategoryService categoryService;

//    首页跳转
    @RequestMapping("/blogHome")
    public String blogHome(Model  model) {

        Admin admin = AdminTokenInterceptor.threadLocal.get();
        log.info("用户名：{}",admin.getUsername());
        model.addAttribute("admin",admin);
        return "blogHome";
    }

//    全部动态
    @GetMapping("/articleList")
    public String articleList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Model model) {

        // 创建分页对象
        Page<Article> page = new Page<>(pageNum, pageSize);

        // 执行分页查询
        IPage<Article> articlePage = articleService.page(
                page,
                Wrappers.<Article>lambdaQuery()
                        .eq(Article::getStatus, Article.ArticleStatus.PUBLISHED.getCode())
                        .orderByDesc(Article::getCreateTime)
        );

        log.info("文章列表：当前页={}, 总页数={}, 总记录数={}",
                articlePage.getCurrent(), articlePage.getPages(), articlePage.getTotal());

        // 将分页结果添加到模型中
//        model.addAttribute("articlePage", articlePage);
//        model.addAttribute("articleList", articlePage.getRecords());
//        model.addAttribute("pageNum", pageNum);
//        model.addAttribute("pageSize", pageSize);
        model.addAttribute("articlePage", articlePage);

        return "blogList";
    }

//    动态详情
    @GetMapping("/articleDetail")
    public String articleDetail(
            @RequestParam(defaultValue = "1") Integer id,
            Model model) {

        Article article = articleService.getById(id);
        model.addAttribute("article", article);
        return "blogArticle";
    }

//    文章管理
    @GetMapping("/articleManage")
    public String articleManage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Model model) {
        // 创建分页对象
        Page<Article> page = new Page<>(pageNum, pageSize);

        // 执行分页查询
        IPage<Article> articlePage = articleService.page(
                page,
                Wrappers.<Article>lambdaQuery()
                        .orderByDesc(Article::getCreateTime)
        );
        articlePage.getRecords().stream().peek(article -> {
            article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());
        }).collect(Collectors.toList());
        log.info("文章列表：当前页={}, 总页数={}, 总记录数={},记录={}",
                articlePage.getCurrent(), articlePage.getPages(), articlePage.getTotal(), articlePage.getRecords());
        model.addAttribute("articlePage", articlePage);

        return "articleManage";
    }

//    文章删除
    @ResponseBody
    @PostMapping("/articleDelete")
    public ResEnum articleDelete(
            @RequestParam(defaultValue = "1") Long articleId,
            Model model) {
        log.info("删除文章：{}", articleId);
        boolean result = articleService.removeById(articleId);
        log.info("删除结果：{}", result);
        if (result) {
            return ResEnum.DELETE_SUCCESS;
        } else {
            return ResEnum.DELETE_ERROR;
        }
    }

//    文章查询通过id查询
    @GetMapping("/articleSeachById")
    public String articleSeachById(
            @RequestParam(defaultValue = "1") Long articleId,
            Model model) {
        Article article = articleService.getById(articleId);
        model.addAttribute("article", article);
        article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());

        return "articleManage";
    }

//    通过状态查询文章
    @GetMapping("/articleSeachByStatus/{status}")
    public String articleSeachByStatus(
            @PathVariable Integer status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Model model) {

        Page<Article> page = new Page<>(pageNum, pageSize);
        IPage<Article> articlePage = articleService.page(
                page,
                Wrappers.<Article>lambdaQuery()
                        .eq(Article::getStatus, status)
                        .orderByDesc(Article::getCreateTime)
        );
        articlePage.getRecords().stream().peek(article -> {
            article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());
        }).collect(Collectors.toList());
//        log.info("文章列表：当前页={}, 总页数={}, 总记录数={}",
//                articlePage.getCurrent(), articlePage.getPages(), articlePage.getTotal());

        model.addAttribute("articlePage", articlePage);

        return "articleManage";
    }

//    查询通过文章标题
    @GetMapping("/articleSeachByTitle")
    public String articleSeachByTitle(
            @RequestParam(defaultValue = "1") String articleTitle,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Model model) {

        log.info("搜索文章：{}", articleTitle);
        Page<Article> page = new Page<>(pageNum, pageSize);
        IPage<Article>  articlePage = articleService.page(page, Wrappers.<Article>lambdaQuery().like(Article::getTitle, articleTitle));

        log.info("文章列表：当前页={}, 总页数={}, 总记录数={}",
                articlePage.getCurrent(), articlePage.getPages(), articlePage.getTotal());
        articlePage.getRecords().stream().peek(article -> {
            article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());
        }).collect(Collectors.toList());
        model.addAttribute("articlePage", articlePage);
        return "articleManage";
    }

    /*
    *   去到文章发布页面
    *
    * */
    @GetMapping("/articleCreate")
    public String articleCreate(Model model) {
        // 创建新的空文章对象
        Article article = new Article();
        model.addAttribute("article", article);
        return "articleEdit";
    }

//    文章编辑
    @GetMapping("/articleEdit")
    public String articleEdit(@RequestParam Long id, Model model) {
        Article article = articleService.getById(id);
        if (article == null) {
            // 如果文章不存在，重定向到文章管理页面
            return "redirect:/articleManage";
        }
        model.addAttribute("article", article);
        return "articleEdit";
    }

//    文章保存
    @ResponseBody
    @PostMapping("/articleCreate")
    public ResEnum articleCreate(@RequestBody Article article) {
        log.info("文章保存：{}", article);
        try {
            // 设置创建时间
            article.setCreateTime(LocalDateTime.now());
            article.setUpdateTime(LocalDateTime.now());
            article.setPublishTime(LocalDateTime.now());

            // 设置作者ID（这里假设从登录用户获取）
            Admin admin = AdminTokenInterceptor.threadLocal.get();
            if (admin != null) {
                article.setAuthorId(admin.getId());
            }
            if (article.getCategoryId() == null) {
                article.setCategoryId(11L);
            }

            log.info("文章保存：{}", article);
            // 保存文章
            boolean result = articleService.saveArticle(article);
            if (result) {
                log.info("文章创建成功，ID: {}", article.getId());
                return ResEnum.SUCCESS;
            } else {
                log.error("文章创建失败");
                return ResEnum.ERROR;
            }
        } catch (Exception e) {
            log.error("文章创建异常", e);
            return ResEnum.ERROR;
        }
    }

    /*
    *   文章更新
    * */
    @ResponseBody
    @PostMapping("/articleUpdate")
    public ResEnum articleUpdate(@RequestBody Article article) {
        try {
            // 设置更新时间
            article.setUpdateTime(LocalDateTime.now());

            // 更新文章
            boolean updated = articleService.updateById(article);
            if (updated) {
                log.info("文章更新成功，ID: {}", article.getId());
                return ResEnum.SUCCESS;
            } else {
                log.error("文章更新失败");
                return ResEnum.ERROR;
            }
        } catch (Exception e) {
            log.error("文章更新异常", e);
            return ResEnum.ERROR;
        }
    }



}
